import axios from 'axios';
import dialog from '@/util/dialog';

export const HTTP_METHOD = {
  GET: 'get',
  POST: 'post',
  FORM: 'formPost'
}

const cacheLink = {};
axios.interceptors.response.use((response) => {
  const url = response.config.url;
  delete cacheLink[url || ''];
  return response;
});


function errorTip(msg, silent) {
  if (!silent && msg) {
    dialog.error(msg);
  }
}

/**
 * 发起请求
 * @param url 请求地址
 * @param data 请求参数
 * @param method http method
 * @param silent 接口请求错误时，不自动提示错误
 */
function request(url, data = {}, method = HTTP_METHOD.GET, silent = false) {
  let headers = data.headers || {};
  delete data.headers;

  let contentType = 'application/json;charset=utf-8';
  if (method === HTTP_METHOD.FORM) {
    contentType = 'application/x-www-form-urlencoded;charset=UTF-8';
    method = HTTP_METHOD.POST;
  }

  headers = {
    'Cache-Control': 'no-cache',
    'Content-type': contentType,
    ...headers
  };

  const { CancelToken } = axios;
  const source = CancelToken.source();
  const cacheSource = cacheLink[url || ''];
  if (cacheSource) {
    source.cancel();
  } else {
    cacheLink[url] = source;
  }

  return axios.request({
    url,
    method,
    params: method === HTTP_METHOD.GET ? data: {},
    data: method === HTTP_METHOD.POST ? data: {},
    timeout: 30000,
    headers: {
      ...headers
    },
    cancelToken: source.token
  }).then(res => res.data);
}

export default {
  /**
   * get请求
   * @param url
   * @param data
   * @returns {Promise<unknown>}
   */
  get(url, data) {
    return request(url, data, HTTP_METHOD.GET);
  },

  /**
   * get请求，错误不自动提示，不自动跳登录
   * @param url
   * @param data
   * @returns {Promise<unknown>}
   */
  getSilent(url, data) {
    return request(url, data, HTTP_METHOD.GET, true);
  },

  /**
   * post请求
   * @param url
   * @param data
   * @returns {Promise<unknown>}
   */
  post(url, data) {
    return request(url, data, HTTP_METHOD.POST);
  },

  /**
   * post请求，错误不自动提示，不自动跳登录
   * @param url
   * @param data
   * @returns {Promise<unknown>}
   */
  postSilent(url, data) {
    return request(url, data, HTTP_METHOD.POST, true);
  },

  /**
   * 表单提交
   * @param url
   * @param data
   * @returns {Promise<unknown>}
   */
  form(url, data) {
    return request(url, data, HTTP_METHOD.FORM, false);
  }
};
